package com.hylanda.config.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.hylanda.util.http.RequestUtils;

/** 
 * @author zhangy
 * @E-mail:blackoon88@gmail.com 
 * @qq:846579287
 * @version created at：2017年11月16日 下午2:25:53 
 * note
 */
@Component
public class RequestInterceptor implements HandlerInterceptor {
    //请求日志实体标识
    private static final String LOGGER_ENTITY = "_logger_entity";
    private static Logger logger = LoggerFactory.getLogger("request_log");
    @Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
    	Device device=(Device)request.getAttribute(DeviceUtils.CURRENT_DEVICE_ATTRIBUTE);
    	String deviceType=null;
    	 if(device.isNormal())
             deviceType = "normal";//Pc端
         else if (device.isMobile())
             deviceType = "mobile";//手机端
         else if (device.isTablet())
             deviceType = "tablet";//平板
    	 System.out.println(deviceType);
    	JSONObject logger = new JSONObject();
        //获取请求sessionId
        String sessionId = request.getRequestedSessionId();
        //请求路径
        String url = request.getRequestURI();
        //获取请求参数信息
//        String paramData = JSON.toJSONString(request.getParameterMap(),SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteMapNullValue);
        //设置客户端ip
        logger.put("ClientIp",RequestUtils.getCliectIp(request));
        //设置请求方法
        logger.put("request_method",request.getMethod());
        //设置请求类型(json|普通请求)
//        logger.put("type",RequestUtils.getRequestType(request));
        //设置请求参数内容json字符串
//        logger.put("paramData",paramData);
        //设置请求地址
        logger.put("uri",url);
        //设置sessionId
        logger.put("sessionId",sessionId);
        //设置请求开始时间
        logger.put("sendTime",System.currentTimeMillis());
        //设置请求实体到request内，方面afterCompletion方法调用
        request.setAttribute(LOGGER_ENTITY,logger);
        return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {

	}

	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
      //获取请求码
        int status = response.getStatus();
        //当前时间
        long currentTime = System.currentTimeMillis();
        //获取本次请求日志实体
        JSONObject loggerEntity = (JSONObject) request.getAttribute(LOGGER_ENTITY);
        //请求开始时间
        long time = loggerEntity.getLongValue("sendTime");
        //设置请求时间差
        long timeConsuming=currentTime - time;
        //打出日志
        //127.0.0.1 -  -  [2017-09-04 19:05:12,538] "POST http://s.wisdom.www.sogou.com/sugg?ifc=4&em=4 HTTP/1.1" 500 4769  16 16
        StringBuilder losb=new StringBuilder();
        losb.append(loggerEntity.getString("ClientIp")).append(" -  -  [");
//        losb.append(DateUtils.longtoString(loggerEntity.getLongValue(("sendTime")))).append("] '").append(loggerEntity.getString("request_method"));
        losb.append(" ").append(loggerEntity.getString("uri")).append("' ").append(status).append(" ").append(timeConsuming);
        logger.info(losb.toString());
        loggerEntity=null;
	}
}
